package com.hsr.web.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.extension.api.R;
import com.hsr.web.dto.*;
import com.hsr.web.entity.TMenu;
import com.hsr.web.service.ITMenuService;
import com.hsr.web.utils.ResultVOUtil;
import com.hsr.web.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tb
 * @since 2022-04-05
 */
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单相关接口")
public class TMenuController {

    @Autowired
    ITMenuService menuService;

//    @GetMapping("/list")
//    @ApiOperation("查询")
//    public ResultVO list(MenuQuery query) {
//        return ResultVOUtil.success(menuService.getList(query));
//    }

    @GetMapping("/list")
    @ApiOperation("菜单树")
    public ResultVO listForTree() {
        List<TreeNode> treeNodes = createTree(menuService.list());
        return ResultVOUtil.success(treeNodes);
    }


    @PutMapping
    @ApiOperation("新增")
    public ResultVO insert(@RequestBody MenuDTO menuDTO){
        TMenu menu = new TMenu();
        BeanUtils.copyProperties(menuDTO,menu);
        menuService.save(menu);
        return ResultVOUtil.success();
    }

    @PutMapping("/{id}")
    @ApiOperation("编辑")
    public ResultVO update(@RequestBody MenuDTO menuDTO,@PathVariable String id){
        menuDTO.setId(id);
        TMenu menu = new TMenu();
        BeanUtils.copyProperties(menuDTO,menu);
        menuService.updateById(menu);
        return ResultVOUtil.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除")
    public ResultVO delete(@PathVariable String id){
        menuService.removeById(id);
        return ResultVOUtil.success();
    }

    private List<TreeNode> createTree(List<TMenu> list) {
        if(CollectionUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        Map<String, List<TMenu>> menus = list.stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getParentId()).orElse("")));
        List<TMenu> rootMenus = menus.get("");
        if(CollectionUtil.isEmpty(rootMenus)){
            return null;
        }

        List<TreeNode> treeNodes = new ArrayList<>();
        for (TMenu rootMenu : rootMenus) {
            TreeNode rootNode = menuTranToTreeNode(rootMenu);
            addChildren(rootNode,menus);
            treeNodes.add(rootNode);
        }
        return treeNodes;
    }

    private TreeNode menuTranToTreeNode(TMenu menu){
        return TreeNode.builder()
                .id(menu.getId())
                .name(menu.getMenuName())
                .status(menu.getMenuState())
                .url(menu.getMenuUrl())
                .build();

    }

    private void addChildren(TreeNode rootNode, Map<String, List<TMenu>> menuMap) {
        List<TMenu> menus = menuMap.get(rootNode.getId());
        if(CollectionUtil.isEmpty(menus)){
            return;
        }
        List<TreeNode> treeNodes = new ArrayList<>();
        for (TMenu menu : menus) {
            TreeNode currentNode = menuTranToTreeNode(menu);
            addChildren(currentNode,menuMap);
            treeNodes.add(currentNode);
        }
        rootNode.setChildren(treeNodes);
    }
}
